package org.lhl.readruler

import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.view.animation.Animation.RELATIVE_TO_SELF
import android.view.animation.RotateAnimation
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_device.*
import kotlinx.android.synthetic.main.item_recyclerview_bluetooth.view.*
import kotlinx.android.synthetic.main.toolbar.*
import lhl.kotlinextends.*
import org.lhl.readruler.connection.ConnectState
import org.lhl.readruler.connection.Event
import org.lhl.readruler.manager.DeviceManager
import org.lhl.readruler.manager.MyLocationManager
import org.lhl.readruler.manager.MyLocationManager.REQUEST_CODE_GPS
import org.lhl.readruler.utils.position
import org.lhl.readruler.widget.RecyclerAdapter
import java.util.concurrent.TimeUnit

class DeviceActivity : BaseActivity() {

    private val deviceList = mutableListOf<BluetoothDevice>()

    private var connectingPos = -1

    private var isFilter = AppConfig.isFilterDevice

    private val anim by lazy {
        RotateAnimation(0f, 359f, RELATIVE_TO_SELF, 0.5f, RELATIVE_TO_SELF, 0.5f).apply {
            repeatCount = -1
            duration = 500
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_device)
        tvTitle.text = "设备连接"
        imgBack.click { finish() }

        if (!MyLocationManager.isGpsEnable()) {
            "请先打开GPS".toastLong()
            val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
            startActivityForResult(intent, REQUEST_CODE_GPS)
        }

        switchFilter.isChecked = isFilter
        switchFilter.setOnCheckedChangeListener { buttonView, isChecked ->
            AppConfig.isFilterDevice = isChecked
            isFilter = isChecked
            if (isFilter) {
                deviceList.filter { it.name != null && it.name.startsWith("NBK", true) }.let {
                    deviceList.clear()
                    deviceList.addAll(it)
                }
                rcyBluetooth.adapter?.notifyDataSetChanged()
            }
        }

        switchBluetooth.setOnCheckedChangeListener { buttonView, isChecked ->

            "switchBluetooth  $isChecked".e()

            llDiscover.visible = isChecked
            switchBluetooth.isEnabled = false
            if (isChecked) {
                DeviceManager.openBluetooth().observeOn(AndroidSchedulers.mainThread()).doOnComplete {
                    switchBluetooth.isEnabled = true
                    DeviceManager.startDiscover()
                }.subscribe().auto("openBluetooth")
                return@setOnCheckedChangeListener
            }
            deviceList.clear()
            rcyBluetooth.adapter?.notifyDataSetChanged()
            DeviceManager.closeBluetooth().observeOn(AndroidSchedulers.mainThread()).doOnComplete {
                switchBluetooth.isEnabled = true
            }.subscribe().auto("closeBluetooth")
        }

        imgRefresh.click(1000) {
            if (!DeviceManager.isOpenBluetooth()) {
                "蓝牙未打开或正在开启中".toast()
                return@click
            }
            imgRefresh.startAnimation(anim)
            imgRefresh.postDelayed({
                imgRefresh.clearAnimation()
            }, 1000)

            connectingPos = -1
            DeviceManager.stopDiscover()
            deviceList.clear()
            rcyBluetooth.adapter?.notifyDataSetChanged()
            DeviceManager.startDiscover()
        }

        rcyBluetooth.adapter = RecyclerAdapter(deviceList, R.layout.item_recyclerview_bluetooth) {
            val name = it.name ?: "null"
            val isConnecting = connectingPos == position
            tvName.text = name
            tvMac.text = it.address
            imgRuler.visible = name.startsWith("NBK")

            tvConnectingText.visible = isConnecting
            tvConnectingText.text = when (DeviceManager.connectState()) {
                ConnectState.CONNECTED -> "已连接"
                ConnectState.CONNECTING -> "正在连接..."
                else -> "未连接"
            }
            if (isConnecting) {
                imgBluetooth.setImageResource(R.drawable.ic_bluetooth_blue)
                tvName.setTextColor(resources.getColor(R.color.colorPrimary))
                tvMac.setTextColor(resources.getColor(R.color.colorPrimary))
            } else {
                imgBluetooth.setImageResource(R.drawable.ic_bluetooth_n)
                tvName.setTextColor(resources.getColor(R.color.normal))
                tvMac.setTextColor(resources.getColor(R.color.gray))
            }

        }.setOnItemClickListener {

            if (DeviceManager.isConnecting()) {
                "正在连接中..".toast()
                return@setOnItemClickListener
            }
            if (DeviceManager.isConnected() && connectingPos == position) {
                "设备已连接".toast()
                return@setOnItemClickListener
            }

            DeviceManager.disConnect()
            Observable.timer(50, TimeUnit.MILLISECONDS).repeatUntil { DeviceManager.isDisConnect() }
                .observeOn(AndroidSchedulers.mainThread())
                .doOnComplete {
                    connectingPos = position
                    rcyBluetooth.adapter?.notifyDataSetChanged()
                    DeviceManager.connect(deviceList[position])
                }.subscribe().auto("disConnect")
        }


        DeviceManager.registerBleDiscoverListener()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (isFilter && (it.name == null || !it.name.startsWith("NBK", true))) return@subscribe
                if (deviceList.contains(it)) return@subscribe
                deviceList.add(it)
                rcyBluetooth.adapter?.notifyDataSetChanged()
            }.auto("discoverDevice")

        DeviceManager.registerChangeListener()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                when (it.attribute) {
                    Event.CONNECTED -> {
                        rcyBluetooth.adapter?.notifyItemChanged(connectingPos)
                        tvConnectName.text = deviceList[connectingPos].name ?: "null"
                        tvConnectMac.text = deviceList[connectingPos].address
                        llConnected.visible = true
                    }
                    Event.DISCONNECTED -> {
                        "已断开当前连接".toast()
                        llConnected.visible = false
                        connectingPos = -1
                        rcyBluetooth.adapter?.notifyDataSetChanged()
                    }
                    Event.CONNECT_TIMEOUT -> {
                        "连接超时".toast()
                        llConnected.visible = false
                        connectingPos = -1
                        rcyBluetooth.adapter?.notifyDataSetChanged()
                    }
                    Event.DEVICE_ID -> {
                        tvDeviceId.text = DeviceManager.deviceId ?: ""
                        tvDeviceState.text = DeviceManager.deviceState
                        if (DeviceManager.isInvalidDevice)
                            tvDeviceState.setTextColor(resources.getColor(R.color.warningRed))
                        else
                            tvDeviceState.setTextColor(resources.getColor(R.color.colorPrimary))
                    }
                }
            }.auto("registerChangeListener")

        switchBluetooth.isChecked = DeviceManager.isOpenBluetooth()

        llConnected.visible = DeviceManager.isConnected()
        tvConnectName.text = DeviceManager.device?.name ?: ""
        tvConnectMac.text = DeviceManager.device?.address ?: ""
        tvDeviceId.text = DeviceManager.deviceId ?: ""
        tvDeviceState.text = DeviceManager.deviceState
        if (DeviceManager.isInvalidDevice)
            tvDeviceState.setTextColor(resources.getColor(R.color.warningRed))
        else
            tvDeviceState.setTextColor(resources.getColor(R.color.colorPrimary))

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_GPS) {
            if (!MyLocationManager.isGpsEnable()) {
                val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                startActivityForResult(intent, REQUEST_CODE_GPS)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        DeviceManager.stopDiscover()
//        MyLocationManager.onStop()
    }
}
